﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrinterMonitorSvc.Common
{
    /// <summary>
    /// 监视器帮助类
    /// </summary>
    public static class WatchHelper
    {
        #region 获取当前方法测量得出的总运行时间（以毫秒为单位）
        /// <summary>
        /// 获取当前方法测量得出的总运行时间（以毫秒为单位）
        /// </summary>
        /// <param name="action">耗时操作</param>
        /// <returns></returns>
        public static long Watch(Action action)
        {
            if (null == action)
            {
                return 0;
            }
            Stopwatch watcher = new Stopwatch();
            watcher.Start();
            action.Invoke();
            watcher.Stop();
            return watcher.ElapsedMilliseconds;

        }
        /// <summary>
        /// 获取当前方法测量得出的总运行时间（以毫秒为单位）
        /// </summary>
        /// <param name="action">耗时操作</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束</param>
        /// <param name="exception">异常信息</param>
        /// <returns></returns>
        public static long Watch(Action action, out DateTime startTime, out DateTime endTime, out Exception exception)
        {
            exception = null;
            startTime = endTime = DateTime.Now;
            if (null == action)
            {
                return 0;
            }
            startTime = DateTime.Now;
            try
            {
                action.Invoke();
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            endTime = DateTime.Now;
            return (long)(endTime - startTime).TotalMilliseconds;
        }
        #endregion
    }
}
